import { observer } from 'mobx-react-lite'
import { useRootStore } from '../context/UserContext';
import { runInAction } from 'mobx';
import { asyncFetchAge } from '../services/UserService';
import { useState, useEffect } from 'react';
 
export const UserView = observer(() => {   //observer is mandatorily required 

    //useState to define component's own model.
    const [loading, setLoading] = useState(false); 

    const { user } = useRootStore();  //destructure RootStore

    //Event Handlers
    const onRename = () => {
        const newName = prompt('User name', user.name) || user.name;

        user.setName(newName);  // Update the client side only.
        // user.name = newName;  //strict mode is not allowed.
        console.log(user.name);
    };

    //Event Handlers
    const onAddAge = () => {

        // user.showLoading(); //loading ...
        setLoading(true);
        runInAction(async () => {   // this function SHOULD be async here!
            user.setAge(await asyncFetchAge(user.age)); //simulate calls thru UserService to backend service.
            console.log(user.age);

            // user.hideLoading(); 
            setLoading(false);
        });
    };

    // 处理输入框值变化的函数
    const onInputChange = (event) => {
    // 更新state变量的值
      user.setName(event.target.value);
    };

    const onInputKeyUp = (event) => {
        if (event.key === 'Enter') {
          // 阻止默认行为，例如表单提交
          event.preventDefault();
          // 检查释放的是否是Enter键

          // 在这里处理Enter键事件
          console.log('Enter released, input value:', event.target.value);

          // 可以在这里执行进一步的操作，比如发送数据到服务器
          
        }
      };

    // 处理表单提交: 按下回车键
    const onSubmit = (event) => {
        event.preventDefault(); // 阻止表单默认提交行为
        
        if (loading)
            return;

        // 执行表单提交逻辑
        setLoading(true);
        runInAction(async () => {   // this function SHOULD be async here!
          user.setAge(await asyncFetchAge(user.age)); //simulate calls thru UserService to backend service.
          console.log(user.age);

          // user.hideLoading(); 
          setLoading(false);

        });

    };


    // useEffect(() => {
    //     const fetchUser = async () => {
    //       const response = await fetch('/api/user');
    //       const data = await response.json();
    //       setUser(data);
    //     };
      
    //     fetchUser();
    //   }, [setUser]); // 添加 setUser 到依赖数组
    useEffect(() => {
        // 在组件加载时自动加载数据
        user.setAge(18)
      }, [user]);

    return (
        <>
            <div>Username: {user.name}</div>
            <button onClick={ onRename } >
                Edit
            </button>
            <br/>

            <form onSubmit={onSubmit}>
                <label htmlFor="username">用户名:</label>
                
                <input type="text" id="username" name="username" value={user.name} onChange={onInputChange} onKeyUp={onInputKeyUp}>
                </input>
                {/* <input type="submit" value="提交" /> */}
            </form>

            <div>ServedYears: {user.servedYears}</div>
            <div>Age: {user.age}</div>
            <button onClick={ onAddAge } disabled={loading} >
                Age++
            </button>
            <div>{user.isLoading ? "Loading..." : ""}</div>
        </>
    )
});    